package com.baton.plugins.finder;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class AddServlet
 */
@WebServlet("/addFinder.java")
public class AddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doPost(request, response);


	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		getResponse(request, response);
	}

	@Override
	public void init() throws ServletException {
		ServletContextFactory.setServletContext(getServletContext());
	}
	
	private void getResponse(HttpServletRequest request,HttpServletResponse response) throws IOException{
		int acount = 1;
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		Map<String,Object> map = new HashMap<String,Object>();
		String command = request.getParameter("command");
		String basePath =  getServletContext().getRealPath("/userfiles/grandid/userid");
		String id = request.getParameter("id");
		id = URLDecoder.decode(id, "UTF-8").replaceAll("\\\\", "/"); 
		String pid = request.getParameter("pid");
		pid = URLDecoder.decode(pid, "UTF-8").replaceAll("\\\\", "/");
		String spid = id.substring(0, 3);
		if("getFiles".equals(command)){
			if(!("/图片".equals(spid) || "/视频".equals(spid)||"/文档".equals(spid))){
				map.put("erro", "0");
				map.put("msg", "不能创建根目录");
				out.println(JSON.toJSONString(map));
				return;

			}
		String path = getServletContext().getRealPath("/userfiles/grandid/userid"  + "/"+id);

		File file = new File(path);
		boolean bfile = file.exists();
		if(bfile == true){
			map.put("msg", "文件已存在");
			map.put("success", false);

		}else{
			bfile = file.mkdirs();
			if(bfile == true){
				map.put("msg", "创建成功");
				map.put("success", true);

			}
		}
		out.println(JSON.toJSONString(map));
	}
	}
}
